<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { Anchor, message } from 'ant-design-vue';

import { getHotelPolicies, updateHotelPolicies } from '#/api';

import CancelPolicy from './components/CancelPolicy.vue';
import CheckInPolicy from './components/CheckInPolicy.vue';
import ChildPolicy from './components/ChildPolicy.vue';
import DepositPolicy from './components/DepositPolicy.vue';
import MealPolicy from './components/MealPolicy.vue';
import PetPolicy from './components/PetPolicy.vue';
import StayPolicy from './components/StayPolicy.vue';

const anchorList = ref([
  {
    key: 'cancelPolicy',
    href: '#cancelPolicy',
    title: '取消政策',
  },
  {
    key: 'checkInPolicy',
    href: '#checkInPolicy',
    title: '入离政策',
  },
  {
    key: 'stayPolicy',
    href: '#stayPolicy',
    title: '住宿规定',
  },
  {
    key: 'childPolicy',
    href: '#childPolicy',
    title: '儿童政策',
  },
  {
    key: 'mealPolicy',
    href: '#mealPolicy',
    title: '早餐信息',
  },
  {
    key: 'petPolicy',
    href: '#petPolicy',
    title: '宠物政策',
  },
  {
    key: 'depositPolicy',
    href: '#depositPolicy',
    title: '押金政策',
  },
]);

// 锚点
const getContainer = () => {
  const container = document.querySelector('#main');
  if (container && container instanceof HTMLElement) {
    return container;
  } else {
    // 返回一个默认的有效的DOM元素或者抛出一个错误
    console.error('Container element not found');
    return document.body; // 或者其他默认的DOM元素
  }
};

// 锚点跳转方法实现
const handleClick = (
  e: { preventDefault: () => void },
  link: { href: string },
) => {
  e.preventDefault();
  if (link.href) {
    // 找到锚点对应得的节点
    const element = document.querySelector(`#${link.href.replace('#', '')}`);
    // 如果对应id的锚点存在，就跳滚动到锚点顶部
    if (element) {
      element.scrollIntoView({
        behavior: 'smooth',
      });
    }
  }
};

interface FormData {
  breakfastEnd?: {
    hour: null | number | string;
    minute: null | number | string;
    nano: null | number | string;
    second: null | number | string;
  };
  breakfastNum: null | number | string;
  breakfastPrice: null | number | string;
  breakfastStart: {
    hour: null | number | string;
    minute: null | number | string;
    nano: null | number | string;
    second: null | number | string;
  };
  breakfastType: null | number | string;
  cancelFeeRate: null | number | string;
  cancelPolicy: null | number | string;
  checkInTime: null | string;
  checkOutTime: null | string;
  createdTime: null | string;
  depositAmount: null | number | string;
  freeCancelHours: null | number | string;
  guestType: null | number | string;
  hotelId: null | number | string;
  id: null | number | string;
  isAllDayFrontDesk: boolean;
  isAllowChildren: boolean;
  isAllowCooking: boolean;
  isAllowParty: boolean;
  isAllowPets: boolean;
  isAllowPhoto: boolean;
  isBreakfast: boolean;
  isDelete: boolean;
  isDeposit: boolean;
  isExtraBed: boolean;
  isQuietTime: boolean;
  minAgeLimit: null | number | string;
  quietTimeEnd: {
    hour: null | number | string;
    minute: null | number | string;
    nano: null | number | string;
    second: null | number | string;
  };
  quietTimeStart: {
    hour: null | number | string;
    minute: null | number | string;
    nano: null | number | string;
    second: null | number | string;
  };
  updatedTime: null | string;
}
// 所有政策的表单数据
const form = ref<FormData>();
// 默认值 因为编辑接口都为一个 所以需要记录一下表单的初始化默认值，防止改动未点击保存的内容
const defaultForm = ref<FormData>();

interface EditKeys {
  [key: string]: boolean; // 定义索引签名，允许任意字符串作为属性名
  cancelPolicy: boolean;
  checkInPolicy: boolean;
  stayPolicy: boolean;
  childPolicy: boolean;
  mealPolicy: boolean;
  petPolicy: boolean;
  depositPolicy: boolean;
}
// 编辑状态，放父组件统一管理，限制一次只能编辑一个
const editStatus = ref<EditKeys>({
  cancelPolicy: false,
  checkInPolicy: false,
  stayPolicy: false,
  childPolicy: false,
  mealPolicy: false,
  petPolicy: false,
  depositPolicy: false,
});

// 获取酒店政策详情
const getPolicies = async () => {
  try {
    const { data } = await getHotelPolicies();
    form.value = data;
    defaultForm.value = { ...data };
  } catch (error) {
    console.error(error);
  }
};

// 表单保存事件
const submit = async (key: string) => {
  try {
    const params = {
      ...defaultForm.value,
      ...form.value,
    };
    await updateHotelPolicies(params);
    message.success('保存成功');
    editStatus.value[key] = false;
    await getPolicies();
  } catch (error) {
    console.error('保存失败：', error);
  }
};

onMounted(() => {
  getPolicies();
});
</script>

<template>
  <div
    class="absolute bottom-0 right-0 flex h-[100%] w-[100%] flex-col overflow-hidden"
  >
    <div id="main" class="main overflow-auto p-4">
      <div class="mb-4 text-2xl font-bold">酒店政策</div>
      <div class="flex justify-between">
        <div class="flex-auto">
          <div id="cancelPolicy" class="card-box mb-3 w-full rounded-md">
            <!-- 免费取消 -->
            <CancelPolicy
              v-model:edit-status="editStatus"
              v-model:form="form"
              @init="getPolicies"
              @submit="submit"
            />
          </div>
          <div id="checkInPolicy" class="card-box mb-3 w-full rounded-md">
            <!-- 入离 -->
            <CheckInPolicy
              v-model:edit-status="editStatus"
              v-model:form="form"
              @init="getPolicies"
              @submit="submit"
            />
          </div>
          <div id="stayPolicy" class="card-box mb-3 w-full rounded-md">
            <!-- 住宿 -->
            <StayPolicy
              v-model:edit-status="editStatus"
              v-model:form="form"
              @init="getPolicies"
              @submit="submit"
            />
          </div>
          <div id="childPolicy" class="card-box mb-3 w-full rounded-md">
            <!-- 儿童 -->
            <ChildPolicy
              v-model:edit-status="editStatus"
              v-model:form="form"
              @init="getPolicies"
              @submit="submit"
            />
          </div>
          <div id="mealPolicy" class="card-box mb-3 w-full rounded-md">
            <!-- 早餐 -->
            <MealPolicy
              v-model:edit-status="editStatus"
              v-model:form="form"
              @init="getPolicies"
              @submit="submit"
            />
          </div>
          <div id="petPolicy" class="card-box mb-3 w-full rounded-md">
            <!-- 宠物 -->
            <PetPolicy
              v-model:edit-status="editStatus"
              v-model:form="form"
              @init="getPolicies"
              @submit="submit"
            />
          </div>
          <div id="depositPolicy" class="card-box mb-3 w-full rounded-md">
            <!-- 押金 -->
            <DepositPolicy
              v-model:edit-status="editStatus"
              v-model:form="form"
              @init="getPolicies"
              @submit="submit"
            />
          </div>
        </div>
        <!-- 右侧悬浮菜单栏 -->
        <div class="ml-2">
          <Anchor
            :get-container="getContainer"
            :items="anchorList"
            wrapper-class="w-[200px] card-box rounded-md p-3"
            @click="handleClick"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.ant-anchor .ant-anchor-link-title) {
  color: hsl(var(--card-foreground));
}

.main {
  flex: 1;
}
</style>
